package com.demo.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.demo.domain.EventEntity;
import org.apache.commons.collections.SetUtils;
import org.apache.flink.shaded.curator.org.apache.curator.shaded.com.google.common.collect.Sets;

import java.util.Objects;
import java.util.Set;

/**
 * @author XINZE
 */
public class LogToEventEntity {

    private static final Set<String> appLibs = Sets.newHashSet("Android", "iOS");
    private static final Set<String> miniProgramLibs = Sets.newHashSet("MiniProgram", "AliPayMini", "AlipayMini");

    public static EventEntity getLog(String s){
        System.out.println(s);
        EventEntity event = new EventEntity();
        if (!s.startsWith("{")) {
            return null;
        }
        JSON json = JSONUtil.parse(s);
        if (Objects.isNull(json)) {
            return null;
        }
        event.setUserId(JSONUtil.getByPath(json, "distinct_id", -1));
        event.setProductId(JSONUtil.getByPath(json, "product_id", -1));
        event.setTime(JSONUtil.getByPath(json, "time", 0L));
        event.setLib(JSONUtil.getByPath(json, "lib", ""));
        event.setTyChannel(JSONUtil.getByPath(json, "ty_channel", 0));

        if (appLibs.contains(event.getLib()) || ("js".equals(event.getLib()) && event.getTyChannel() == 1)) {
            event.setActiveType("app");
        } else if (miniProgramLibs.contains(event.getLib()) ||
                    ("js".equals(event.getLib()) && (event.getTyChannel() == 2 ||event.getTyChannel() == 4 ))) {
            event.setActiveType("mini");
        } else {
            event.setActiveType("unknown");
        }

        System.out.println(JSONUtil.toJsonStr(event));

        return event;
    }
}
